<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use App\Models\Workcorp;
use App\Models\Worklink;
use App\Models\Workqrcode;
use App\Models\Workqrcodeimg;
use App\Models\Worklinkwelcome;
use App\Models\Worklinkhtml;
use App\Models\Memberorders;
use App\Models\Worklinkrecord;
use App\Models\Worklinkstatistic;
use App\Models\Worklinktotal;
use App\Models\Worklinkback;
use App\Models\Usersdomain;
use App\Models\Worklinkurl;
use App\Services\CommonService;
use App\Services\LinkscheckService;
use App\Services\OutputService;
use App\Services\WorkService;
use App\Services\WorkkfService;
use App\Services\HtmlossService;
use App\Services\WorkcustomService;
use App\Services\DeviceService;
use App\Services\WorkerrorService;
use App\Services\WorkdataService;
use App\Services\CacheService;
use Auth,Exception,Log,Config;

class WxkfController extends Controller
{
    public function wxkfList(Request $request)
    {
        $users = Auth::user();
        $workLinks = Worklink::userWorkLinks($users->id);
        return view("admin.wxkf.wxkf_list",["workLinks"=>$workLinks,"condition"=>$request->all()]);
    }

    public function wxkfListAdd(Request $request)
    {
        $users = Auth::user();
        if ($users->disable == 2) {
            Auth::logout();
            return redirect("/admin/login");
        }
        $workCorps = Workcorp::userWorkCorpSample($users->id);
        return view("admin.wxkf.wxkf_list_add",["workCorps"=>$workCorps,"status"=>"create"]);
    }

    public function wxkfListUpdate(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        if ($request->msg_type == 1) {
            $tail_content = empty($request->tail_content) ? "" : $request->tail_content;
            $msgContent = ["msgtype"=>"msgmenu","msgmenu"=>["head_content"=>$request->head_content,"list"=>$request->msgmenu,"tail_content"=>$tail_content]];
        } else {
            $msgContent = ["msgtype"=>"text","text"=>["content"=>$request->text_content]];
        }
        if (empty($request->kfid)) {
            $usersLinksPv = LinkscheckService::getUsersLinksPv($users_id);
            if ($usersLinksPv["status"] == "error") return OutputService::error($usersLinksPv["msg"],"",1005);
            $kfid = CommonService::decb64(time().rand(1000,9999));
            $open_kfid = "";
            if (!empty($request->corp_id)) {
                $media = WorkService::mediaUpload($request->corp_id,"image",$request->kefu_head_img);
                if ($media["errcode"] != 0) {
                    $message = WorkerrorService::getErrorMsg($media["errcode"]);
                    return OutputService::error($message);
                }
                $kfAccount = WorkkfService::kfAccountAdd($request->corp_id,$request->kefu_nike,$media["media_id"]);
                if ($kfAccount->errcode != 0) {
                    $message = WorkerrorService::getErrorMsg($kfAccount->errcode);
                    return OutputService::error($message);
                }
                $open_kfid = $kfAccount->open_kfid;
                $contactWay = WorkkfService::kfAddContactWay($request->corp_id,$open_kfid,$kfid);
                if ($contactWay->errcode != 0) {
                    $message = WorkerrorService::getErrorMsg($contactWay->errcode);
                    return OutputService::error($message);
                }
                $link_url = $contactWay->url;
            } else {
                $link_url = "";
            }
            Worklink::createWorkLink($kfid,$users_id,$request->corp_id,$request->remark,$request->kefu_nike,$request->kefu_head_img,$usersLinksPv["limit_pv"],$usersLinksPv["end_time"],$open_kfid,$link_url);
            $msgContent = json_encode($msgContent);
            Worklinkwelcome::createWorkLinkWelcome($kfid,$request->msg_type,$msgContent);
            Workqrcode::createWorkQrcode($kfid,$request->qrcode_switch,$request->qrcode_upper,$request->qrcode_daily,$request->qrcode_style,$request->qrcode_title,$request->qrcode_nike,$request->qrcode_head_img,$request->qrcode_describe,$request->qrcode_notice);

            if (!empty($request->qrcodeLists)) {
                $qrcodeImages = [];
                $expiration_time = strtotime("+1 year");
                foreach ($request->qrcodeLists as $img_url) {
                    $qrcodeImages[] = ["kfid"=>$kfid,"name"=>"","img_url"=>$img_url,"expiration_time"=>$expiration_time,"count_limit"=>$request->qrcode_upper,"created_at"=>time()];
                }
                Workqrcodeimg::batchCreateWorkQrcodeImg($qrcodeImages);
            }
            return OutputService::success("客服链接创建成功!",["kfid"=>$kfid]);
        } else {
            $kfid = $request->kfid;
            $workLink = Worklink::workLinkDetial($kfid);
            if (empty($workLink)) return OutputService::error("微信链接不存在!");
            if (!empty($request->corp_id)) {
                $media = WorkService::mediaUpload($request->corp_id,"image",$request->kefu_head_img);
                if ($media["errcode"] != 0) {
                    $message = WorkerrorService::getErrorMsg($media["errcode"]);
                    return OutputService::error($message);
                }
                if ($request->corp_id != $request->corp_id_old) {
                    $kfAccount = WorkkfService::kfAccountAdd($request->corp_id,$request->kefu_nike,$media["media_id"]);
                    if ($kfAccount->errcode != 0) {
                        $message = WorkerrorService::getErrorMsg($kfAccount->errcode);
                        return OutputService::error($message);
                    }
                    $open_kfid = $kfAccount->open_kfid;
                    $contactWay = WorkkfService::kfAddContactWay($request->corp_id,$open_kfid,$kfid);
                    if ($contactWay->errcode != 0) {
                        $message = WorkerrorService::getErrorMsg($contactWay->errcode);
                        return OutputService::error($message);
                    }
                    $link_url = $contactWay["url"];
                } else {
                    $open_kfid = $workLink->open_kfid;
                    $link_url = $workLink->link_url;
                    $kfAccount = WorkkfService::kfAccountUpdate($request->corp_id,$request->kefu_nike,$media["media_id"],$open_kfid);
                    if ($kfAccount->errcode != 0) {
                        $message = WorkerrorService::getErrorMsg($kfAccount->errcode);
                        return OutputService::error($message);
                    }
                }
            } else {
                $link_url = $workLink->link_url;
            }
            if ($workLink->users_id != $users_id) return OutputService::error("微信链接不存在!");
            Worklink::updateWorkLink($kfid,$request->corp_id,$request->remark,$request->kefu_nike,$request->kefu_head_img,$open_kfid,$link_url);
            $msgContent = json_encode($msgContent);
            Worklinkwelcome::updateWorkLinkWelcome($kfid,$request->msg_type,$msgContent);
            Workqrcode::updateWorkQrcode($kfid,$request->qrcode_switch,$request->qrcode_upper,$request->qrcode_daily,$request->qrcode_style,$request->qrcode_title,$request->qrcode_nike,$request->qrcode_head_img,$request->qrcode_describe,$request->qrcode_notice);
            Cache::forget("work_link_welcome_".$kfid);
            Cache::forget("work_link_".$kfid);
            return OutputService::success("客服链接更新成功!",["kfid"=>$kfid]);
        }
    }

    public function wxkfUpdate(Request $request,$kfid)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $kfid = $request->kfid;
        $workLink = Worklink::workLinkDetial($kfid);
        if (empty($workLink)) return redirect("/admin/wxkf/wxkf_list")->with("status","error")->with("msg","微信外链不存在!");
        if ($workLink->users_id != $users_id) return redirect("/admin/wxkf/wxkf_list")->with("status","error")->with("msg","微信外链不存在!");
        $workCorps = Workcorp::userWorkCorpSample($users_id);
        $workLinkWelcome = Worklinkwelcome::workLinkWelcome($kfid);
        $workQrcode = Workqrcode::workQrcodeDetial($kfid);
        $workQrcodeImg = Workqrcodeimg::previewWorkQrcodeImg($kfid);
        $qrcodeLists = [];
        if (!empty($workQrcodeImg)) {
            $qrcodeLists[] = $workQrcodeImg->img_url;
        }
        $corp_id = empty($workLink->corp_id) ? "" : $workLink->corp_id;
        $workLinkJson = ["kfid"=>$kfid,"remark"=>$workLink->remark,"kefu_nike"=>$workLink->kefu_nike,"kefu_head_img"=>$workLink->kefu_head_img,"corp_id"=>$corp_id,"corp_id_old"=>$corp_id,"msg_type"=>$workLinkWelcome->msg_type,"qrcode_style"=>$workQrcode->qrcode_style,"qrcode_switch_type"=>$workQrcode->qrcode_switch_type,"qrcode_head_img"=>$workQrcode->qrcode_head_img,"qrcode_title"=>$workQrcode->qrcode_title,"qrcode_nike"=>$workQrcode->qrcode_nike,"qrcode_describe"=>$workQrcode->qrcode_describe,"qrcode_notice"=>$workQrcode->qrcode_notice,"qrcode_switch"=>$workQrcode->switch,"qrcode_upper"=>$workQrcode->upper,"qrcode_daily"=>$workQrcode->daily,"device_bind"=>$workQrcode->device_bind,"text_content"=>"","head_content"=>"","tail_content"=>"","msgmenu"=>[],"qrcodeLists"=>$qrcodeLists];
        $msgContent = json_decode($workLinkWelcome->msg_content,true);
        if ($workLinkWelcome->msg_type == 1) {
            $workLinkJson["head_content"] = $msgContent["msgmenu"]["head_content"];
            $workLinkJson["tail_content"] = $msgContent["msgmenu"]["tail_content"];
            $workLinkJson["msgmenu"] = $msgContent["msgmenu"]["list"];
        } else {
            $workLinkJson["text_content"] = $msgContent["text"]["content"];
        }
        return view("admin.wxkf.wxkf_list_add",["workLinkJson"=>$workLinkJson,"status"=>"update","workCorps"=>$workCorps]);
    }

    public function workLinkDel(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $kfid = $request->kfid;
        $workLink = Worklink::workLinkDetial($kfid);
        if (empty($workLink)) return OutputService::error("微信外链不存在!");
        if ($workLink->users_id != $users_id) return OutputService::error("微信外链不存在!");
        Worklink::workLinkDelect($kfid);
        if (!empty($workLink->open_kfid)) {
            WorkkfService::kfAccountDel($workLink->corp_id,$workLink->open_kfid);
        }
        HtmlossService::aliossKefuHtmlDelete($kfid);
        return OutputService::success("微信外链删除成功!");
    }

    public function workLinkRemark(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $kfid = $request->kfid;
        $workLink = Worklink::workLinkDetial($kfid);
        if (empty($workLink)) return OutputService::error("微信外链不存在!");
        if ($workLink->users_id != $users_id) return OutputService::error("微信外链不存在!");
        Worklink::updateWorkLinkRemark($kfid,$request->remark);
        return OutputService::success("链接备注修改成功!");
    }

    public function wxkfDetial(Request $request,$kfid)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $workLinkDetial = Worklink::workLinkDetials($kfid);
        $sign = CommonService::aesEncryptone($kfid);
        if(empty($workLinkDetial)) return back()->with("status","error")->with("msg","客服链接不存在");
        if ($workLinkDetial->users_id != $users_id) return back()->with("status","error")->with("msg","客服链接不存在");
        $memberOrder = Memberorders::getLastLinksOrders($users_id);
        if (empty($memberOrder) || $memberOrder->end_time <= time()) {
            $product_id = 1;
        } else {
            $product_id = $memberOrder->product_id;
        }
        $workLinkBack = Worklinkback::getAllWorkLinkBack($kfid);
        $backPlatfroms = $workLinkBack->pluck("back_platfrom")->all();
        return view("admin.wxkf.wxkf_detail",["workLinkDetial"=>$workLinkDetial,"sign"=>$sign,"backPlatfroms"=>$backPlatfroms,"product_id"=>$product_id]);
    }

    public function wxkfQrcodes(Request $request)
    {
        if (empty($request->kfid) || empty($request->sign)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"接口异常,请稍后尝试!"]);
        $kfid = CommonService::aesDncryptone($request->sign);
        if ($kfid != $request->kfid) return response()->json(["status"=>"error","code"=>"1002","msg"=>"接口异常,请稍后尝试!"]);
        $wxkfdetails = Worklink::getWorkLinkByKfid($kfid);
        if(empty($wxkfdetails)) return response()->json(["status"=>"error","code"=>"1002","msg"=>"客服链接已删除!"]);
        $users = Auth::user();
        if($wxkfdetails->users_id != $users->id && $users->authority < 3) return response()->json(["status"=>"error","code"=>"1003","msg"=>"无权限查看!"]);
        $limit = empty($request->limit) ? 20 : $request->limit;
        $wxkfqrcodelists = Workqrcodeimg::getWorkQrcodeImgLists($kfid,$limit,$request->name,$request->sort,$request->order);
        return OutputService::success('SUCCESS',["data"=>$wxkfqrcodelists]);
    }
    //批量上传客服二维码
    public function wxkfQrcodesAdd(Request $request)
    {
        $users = Auth::user();
        if (empty($request->kfid)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"参数错误！"]);
        if (empty($request->expiration_time)) return response()->json(["status"=>"error","code"=>"1002","msg"=>"请选择二维码过期时间！"]);
        if (empty($request->rate)) return response()->json(["status"=>"error","code"=>"1003","msg"=>"请设置二维码权重！"]);
        if (empty($request->count_limit)) return response()->json(["status"=>"error","code"=>"1004","msg"=>"请设置二维码访问上限！"]);
        if (empty($request->qrcode)) return response()->json(["status"=>"error","code"=>"1005","msg"=>"请上传二维码！"]);
        if (is_array($request->qrcode) && count($request->qrcode) === 0) return response()->json(["status"=>"error","code"=>"1001","msg"=>"请上传二维码！"]);
        $wxkfdetails = Worklink::getWorkLinkByKfid($request->kfid);
        if(empty($wxkfdetails)) return response()->json(["status"=>"error","code"=>"1002","msg"=>"客服链接已删除!"]);
        if (decrypt($request->users_id) != $wxkfdetails->users_id && $users->authority < 3) return response()->json(["status"=>"error","code"=>"1001","msg"=>"链接不存在！"]);
        $qrcodenumber = Workqrcodeimg::getKfQrcodeCount($request->kfid);
        if($qrcodenumber > 199) return response()->json(["status"=>"error","code"=>"1001","msg"=>"客服子码已达上限"]);
        $qrcodelength = count($request->qrcode);
        if($qrcodelength > 10) return response()->json(["status"=>"error","code"=>"1001","msg"=>"每次不能超过10个二维码"]);
        $arrqocode= [];
        foreach ($request->qrcode as $qrcode) {
            $name = empty($qrcode['name']) ? time() : mb_substr($qrcode['name'],0,15);
            $arrqocode[] = ["kfid"=>$request->kfid,"name"=>$name,"img_url"=>$qrcode['image'],"expiration_time"=>strtotime($request->expiration_time),"count_limit"=>$request->count_limit,"rate"=>$request->rate,"created_at"=>time()];
        }
        Workqrcodeimg::batchCreateWorkQrcodeImg($arrqocode);
        CacheService::removeWorkLinkQrcodeCache($request->kfid);
        $msg = '成功添加了'.$qrcodelength.'个二维码';
        // 清除缓存，加入到二维码循环里
        return response()->json(["status"=>"success","code"=>"1000","msg"=>$msg]);
    }

    public function wxkfQrcodesUpdate(Request $request)
    {
        $users = Auth::user();
        if (empty($request->id)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"参数错误！"]);
        if (empty($request->kfid)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"参数错误！"]);
        if (empty($request->expiration_time)) return response()->json(["status"=>"error","code"=>"1002","msg"=>"请选择二维码过期时间！"]);
        if (empty($request->rate)) return response()->json(["status"=>"error","code"=>"1003","msg"=>"请设置二维码权重！"]);
        if (empty($request->count_limit)) return response()->json(["status"=>"error","code"=>"1004","msg"=>"请设置二维码访问上限！"]);
        $wxkfdetails = Worklink::getWorkLinkByKfid($request->kfid);
        if(empty($wxkfdetails)) return response()->json(["status"=>"error","code"=>"1004","msg"=>"客服链接已删除!"]);
        if (decrypt($request->users_id) != $wxkfdetails->users_id && $users->authority < 3) return response()->json(["status"=>"error","code"=>"1001","msg"=>"链接不存在！"]);
        $kfimgdetails = Workqrcodeimg::getKfImgById($request->id);
        if(empty($kfimgdetails)) return response()->json(["status"=>"error","code"=>"1005","msg"=>"该子码已删除!"]);
        $updata = ["expiration_time"=>strtotime($request->expiration_time),"rate"=>$request->rate,"count_limit"=>$request->count_limit,"name"=>$request->qrcode_name];
        Workqrcodeimg::updateWorkQrcodeImg($request->id,$updata);
        // 清除缓存，加入到二维码循环里
        CacheService::removeWorkLinkQrcodeCache($request->kfid);
        return response()->json(["status"=>"success","code"=>"1000","msg"=>'子二维码更新成功']);
    }

    public function wxkfQrcodesDelete(Request $request){
        $users = Auth::user();
        if (empty($request->id)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"参数错误！"]);
        if (empty($request->kfid)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"参数错误！"]);
        $wxkfdetails = Worklink::getWorkLinkByKfid($request->kfid);
        if(empty($wxkfdetails)) return response()->json(["status"=>"error","code"=>"1004","msg"=>"客服链接不存在!"]);
        if (decrypt($request->users_id) != $wxkfdetails->users_id && $users->authority < 3) return response()->json(["status"=>"error","code"=>"1001","msg"=>"链接不存在！"]);
        $kfimgdetails = Workqrcodeimg::getKfImgById($request->id);
        if(empty($kfimgdetails)) return response()->json(["status"=>"error","code"=>"1005","msg"=>"该子码已删除!"]);
        $updata = ["status"=>3];
        Workqrcodeimg::updateWorkQrcodeImg($request->id,$updata);
        // 清除缓存，加入到二维码循环里
        CacheService::removeWorkLinkQrcodeCache($request->kfid);
        return response()->json(["status"=>"success","code"=>"1000","msg"=>'子二维码删除成功']);
    }

    public function wxkfRecords(Request $request)
    {
        $kfid = CommonService::aesDncryptone($request->sign);
        if ($kfid != $request->kfid) return response()->json(["status"=>"error","code"=>"1001","msg"=>"接口异常,请稍后尝试!"]);
        $start_time = strtotime($request->start_time);
        $end_time = strtotime($request->end_time);
        $startMonth = date("m",$start_time);
        $endMonth = date("m",$end_time);
        if ($startMonth == $endMonth) {
            // 在同一月内
            $startTbnum = ($startMonth%4);
            $kfRecordDb = new Worklinkrecord(["tbnum"=>$startTbnum]);
            $kfRecords = $kfRecordDb->workLinkRecordLists($request->kfid,$request->qrcode_show_time,$request->qrcode_press_time,$request->qrcode_card_time,$start_time,$end_time,$request->code,$request->province);
            return OutputService::success("SUCCESS",$kfRecords);
        } else {
            // 在不同月份
            if (empty($request->total)) {
                $startTbnum = ($startMonth%4);
                $startKfRecordDb = new Worklinkrecord(["tbnum"=>$startTbnum]);

                $endTbnum = ($endMonth%4);
                $endKfRecordDb = new Worklinkrecord(["tbnum"=>$endTbnum]);
                // 计算开始的时间
                $startCount = $startKfRecordDb->workLinkRecordListSampleCount($request->kfid,$request->qrcode_show_time,$request->qrcode_press_time,$request->qrcode_card_time,$start_time,$end_time,$request->code,$request->province);
                $endCount = $endKfRecordDb->workLinkRecordListSampleCount($request->kfid,$request->qrcode_show_time,$request->qrcode_press_time,$request->qrcode_card_time,$start_time,$end_time,$request->code,$request->province);
                $total = $startCount+$endCount;
            } else {
                $total = $request->total;
                $startCount = $request->total_start;
                $endCount = $request->total_end;
            }
            if ($request->offset > $endCount) {
                // 第二个库查询结束,查询第一个库
                $startTbnum = ($startMonth%4);
                $startKfRecordDb = new Worklinkrecord(["tbnum"=>$startTbnum]);
                $kfRecords = $startKfRecordDb->workLinkRecordListSample($request->kfid,$request->qrcode_show_time,$request->qrcode_press_time,$request->qrcode_card_time,$start_time,$end_time,$request->offset,$request->limit,$request->code,$request->province);
            } else {
                if (($request->offset+$request->limit) > $endCount) {
                    // 第二个库查询剩余不足,查询1个库
                    // 先查询第二个库
                    $endTbnum = ($endMonth%4);
                    $endKfRecordDb = new Worklinkrecord(["tbnum"=>$endTbnum]);
                    $endkfRecords = $endKfRecordDb->workLinkRecordListSample($request->kfid,$request->qrcode_show_time,$request->qrcode_press_time,$request->qrcode_card_time,$start_time,$end_time,$request->offset,$request->limit,$request->code,$request->province);

                    // 再查询第一个库
                    $newOffset = 0;
                    $newLimit = $request->limit - count($endkfRecords);
                    $startTbnum = ($startMonth%4);
                    $startKfRecordDb = new Worklinkrecord(["tbnum"=>$startTbnum]);
                    $startkfRecords = $startKfRecordDb->workLinkRecordListSample($request->kfid,$request->qrcode_show_time,$request->qrcode_press_time,$request->qrcode_card_time,$start_time,$end_time,$newOffset,$newLimit,$request->code,$request->province);
                    $kfRecords = $endkfRecords->merge($startkfRecords)->all();
                } else {
                    // 查询第二个库
                    $endTbnum = ($endMonth%4);
                    $endKfRecordDb = new Worklinkrecord(["tbnum"=>$endTbnum]);
                    $kfRecords = $endKfRecordDb->workLinkRecordListSample($request->kfid,$request->qrcode_show_time,$request->qrcode_press_time,$request->qrcode_card_time,$start_time,$end_time,$request->offset,$request->limit,$request->code,$request->province);
                }
            }
            return OutputService::success("SUCCESS",["data"=>$kfRecords,"total"=>$total,"total_start"=>$startCount,"total_end"=>$endCount]);
        }
    }

    public function wxkfStatistic(Request $request)
    {
        if (empty($request->kfid)) return OutputService::error("接口异常,请稍后尝试!");
        if (empty($request->date_start)) return OutputService::error("接口异常,请稍后尝试!");
        if (empty($request->date_end)) return OutputService::error("接口异常,请稍后尝试!");
        $users = Auth::user();
        $wxkfdetails = Worklink::getWorkLinkByKfid($request->kfid);
        if(empty($wxkfdetails)) return response()->json(["status"=>"error","code"=>"1002","msg"=>"客服链接已删除!"]);
        if ($wxkfdetails->users_id != decrypt($request->users_id) && $users->authority < 3) return OutputService::error("链接不存在或已删除!");
        $dateLists = CommonService::getDateFromRange($request->date_start,$request->date_end,"Ymd");
        $phases = CommonService::getDateFromRange($request->date_start,$request->date_end,"Ymd");
        $statistics = [];
        // 按天查询
        $lastdatas = Worklinkstatistic::getDailyWorkLinksStatistics($request->kfid,$phases);
        foreach ($dateLists as $dateList) {
            $phase = str_replace("-", "", $dateList);
            $lastdata = $lastdatas->where("phase",$phase)->first();
            if (empty($lastdata)) {
                $statistics[] = ["web"=>0,"click"=>0,"kefu"=>0,"qrcode_show"=>0,"qrcode_press"=>0,"qrcode_card"=>0,"qrcode_add"=>0,"phase"=>$dateList];
            } else {
                $statistics[] = ["web"=>$lastdata->web,"click"=>$lastdata->click,"kefu"=>$lastdata->kefu,"qrcode_show"=>$lastdata->qrcode_show,"qrcode_press"=>$lastdata->qrcode_press,"qrcode_card"=>$lastdata->qrcode_card,"qrcode_add"=>$lastdata->qrcode_add,"phase"=>$dateList];
            }
        }
        return OutputService::success("SUCCESS",["statistics"=>$statistics]);
    }

    public function wxkfTotalStatistic(Request $request)
    {
        if (empty($request->kfid)) return OutputService::error("接口异常,请稍后尝试!");
        $users = Auth::user();
        $wxkfdetails = Worklink::getWorkLinkByKfid($request->kfid);
        if(empty($wxkfdetails)) return response()->json(["status"=>"error","code"=>"1002","msg"=>"客服链接已删除!"]);
        if ($wxkfdetails->users_id != decrypt($request->users_id) && $users->authority < 3) return OutputService::error("链接不存在或已删除!");
        $today = date("Ymd",time());
        $web = Redis::hget('work_page_view_'.$today, $request->kfid);
        $web = $web ? $web : 0;
        $click = Redis::hget('work_click_'.$today, $request->kfid);
        $click = $click ? $click : 0;
        $kefu = Redis::hget('work_kefu_'.$today, $request->kfid);
        $kefu = $kefu ? $kefu : 0;
        $qrcode_show = Redis::hget('work_qrcode_show'.$today, $request->kfid);
        $qrcode_show = $qrcode_show ? $qrcode_show : 0;
        $qrcode_press = Redis::hget('work_qrcode_press_'.$today, $request->kfid);
        $qrcode_press = $qrcode_press ? $qrcode_press : 0;
        $qrcode_card = Redis::hget('work_qrcode_press_card_'.$today, $request->kfid);
        $qrcode_card = $qrcode_card ? $qrcode_card : 0;
        $totalStatic = Worklinktotal::getWorkLinkTotal($request->kfid);
        if (empty($totalStatic)) {
             Worklinktotal::createWorkLinkTotal($request->kfid);
             $totalStatic = (object)["web"=>0,"click"=>0,"kefu"=>0,"qrcode_show"=>0,"qrcode_press"=>0,"qrcode_card"=>0];
        }
        return OutputService::success("SUCCESS",["totalStatic"=>["web"=>$totalStatic->web,"click"=>$totalStatic->click,"kefu"=>$totalStatic->kefu,"qrcode_show"=>$totalStatic->qrcode_show,"qrcode_press"=>$totalStatic->qrcode_press,"qrcode_card"=>$totalStatic->qrcode_card],"todayStatic"=>["web"=>$web,"click"=>$click,"kefu"=>$kefu,"qrcode_show"=>$qrcode_show,"qrcode_press"=>$qrcode_press,"qrcode_card"=>$qrcode_card]]);
    }

    public function WxkfOtherStatistic(Request $request)
    {
        if (empty($request->kfid)) return OutputService::error("接口异常,请稍后尝试!");
        $users = Auth::user();
        $wxkfdetails = Worklink::getWorkLinkByKfid($request->kfid);
        if(empty($wxkfdetails)) return response()->json(["status"=>"error","code"=>"1002","msg"=>"客服链接已删除!"]);
        if ($wxkfdetails->users_id != decrypt($request->users_id) && $users->authority < 3) return OutputService::error("链接不存在或已删除!");
        // 获取数据库编号
        $startMonth = date("m",strtotime($request->other_date_start));
        $tbnum = ($startMonth%4);
        $linkRecordDb = new Worklinkrecord(["tbnum"=>$tbnum]);
        $start_time = strtotime($request->other_date_start);
        $end_time = strtotime($request->other_date_end);
        $kfid = $request->kfid;
        if ($request->other_chart == "system") {
            $systemdatas = $linkRecordDb->getSystemDatas($kfid);
            $systems = DeviceService::systemLists();
            $datas = [];
            foreach ($systemdatas as $systemdata) {
                if (empty($systemdata->system)) {
                    $system = "未知";
                } else {
                    $system = isset($systems[$systemdata->system]) ? $systems[$systemdata->system] : "未知";
                }
                $datas[] = ["value"=>$systemdata->system_count,"name"=>empty($systemdata->system) ? "未知" :$system];
            }
            return OutputService::success("SUCCESS",["datas"=>$datas]);
        } elseif ($request->other_chart == "browser") {
            $browsers = DeviceService::browserNamesLists();
            $systemdatas = $linkRecordDb->getBrowserDatas($kfid);
            $datas = [];
            foreach ($systemdatas as $systemdata) {
                if (empty($systemdata->browser)) {
                    $browser = "未知";
                } else {
                    $browser = isset($browsers[$systemdata->browser]) ? $browsers[$systemdata->browser] : "未知";
                }
                $datas[] = ["value"=>$systemdata->browser_count,"name"=>$browser];
            }
            return OutputService::success("SUCCESS",["datas"=>$datas]);
        } elseif ($request->other_chart == "device") {
            $devices = DeviceService::deviceNames();
            $systemdatas = $linkRecordDb->getDeviceDatas($kfid);
            $datas = [];
            foreach ($systemdatas as $systemdata) {
                if (empty($systemdata->device)) {
                    $device = "未知";
                } else {
                    $device = isset($devices[$systemdata->device]) ? $devices[$systemdata->device] : "未知";
                }
                $datas[] = ["value"=>$systemdata->device_count,"name"=>$device];
            }
            return OutputService::success("SUCCESS",["datas"=>$datas]);
        } elseif ($request->other_chart == "rate") {
            if ($request->diff_day <= 1) {
                $web_time = $linkRecordDb->getDailyCount($kfid,"web_time",$start_time,$end_time);
                $click_time = $linkRecordDb->getDailyCount($kfid,"click_time",$start_time,$end_time);
                $kefu_time = $linkRecordDb->getDailyCount($kfid,"kefu_time",$start_time,$end_time);
                $qrcode_show_time = $linkRecordDb->getDailyCount($kfid,"qrcode_show_time",$start_time,$end_time);
                $qrcode_press_time = $linkRecordDb->getDailyCount($kfid,"qrcode_press_time",$start_time,$end_time);
                $qrcode_card_time = $linkRecordDb->getDailyCount($kfid,"qrcode_card_time",$start_time,$end_time);
            } else {
                $phases = CommonService::getDateFromRange($request->other_date_start,$request->other_date_end,"Ymd");
                $linkStatic = Worklinkstatistic::getDailyWorkLinksStatistics($kfid,$phases);
                $web_time = $linkStatic->sum("web_time");
                $click_time = $linkStatic->sum("click_time");
                $kefu_time = $linkStatic->sum("kefu_time");
                $qrcode_show_time = $linkStatic->sum("qrcode_show_time");
                $qrcode_press_time = $linkStatic->sum("qrcode_press_time");
                $qrcode_card_time = $linkStatic->sum("qrcode_card_time");
            }
            $total = $web_time;
            if ($total == 0) {
                $total_rate = 0;
                $click_rate = 0;
                $kefu_rate = 0;
                $qrcode_show_rate = 0;
                $qrcode_press_rate = 0;
                $qrcode_card_rate = 0;
            } else {
                $total_rate = 100;
                $click_rate = round($click_time/$total,2)*100;
                $kefu_rate = round($kefu_time/$total,2)*100;
                $qrcode_show_rate = round($qrcode_show_time/$total,2)*100;
                $qrcode_press_rate = round($qrcode_press_time/$total,2)*100;
                $qrcode_card_rate = round($qrcode_card_time/$total,2)*100;
            }
            $datas = [["value"=>$total_rate,"name"=>"访问落地页"],["value"=>$click_rate,"name"=>"跳转按钮"],["value"=>$kefu_rate,"name"=>"发送欢迎语"],["value"=>$qrcode_show_rate,"name"=>"二维码展示"],["value"=>$qrcode_press_rate,"name"=>"二维码长按"],["value"=>$qrcode_card_rate,"name"=>"点击名片"]];
            return OutputService::success("SUCCESS",["datas"=>$datas]);
        } elseif ($request->other_chart == "map") {
            $systemdatas = $linkRecordDb->getProvinceDatas($request->kfid);
            $datas = [];
            foreach ($systemdatas as $systemdata) {
                $datas[] = ["value"=>$systemdata->province_count,"name"=>empty($systemdata->province) ? "未知" : $systemdata->province];
            }
            return OutputService::success("SUCCESS",["datas"=>$datas]);
        } else {
            return OutputService::error("参数错误!");
        }
    }

    public function wxkfExample(Request $request)
    {
        return view("admin.wxkf.wxkf_example");
    }

    public function wxkfHtmlUpdate(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $kfid = $request->kfid;
        $workLink = Worklink::workLinkDetial($kfid);
        if (empty($workLink)) return redirect("/admin/wxkf/wxkf_list")->with("status","error")->with("msg","微信外链不存在!");
        if ($workLink->users_id != $users_id) return redirect("/admin/wxkf/wxkf_list")->with("status","error")->with("msg","微信外链不存在!");
        $workLinkHtml = Worklinkhtml::workLinkHtml($kfid);
        if (empty($workLinkHtml)) {
            Worklinkhtml::createWorkLinkHtml($kfid,$workLink->remark,'<div class="edit-htmldom htmldom-activity" id="YY76ERh23nRrHAzHc53w6NjfayXNc7T6" platfrom="img"><img draggable="false" src="https://doye.oss-cn-beijing.aliyuncs.com/uploads/20230201/202302011408065115.jpg" class="site-img-12"></div><div class="edit-htmldom" id="6KAhRPwiWQs4wWwTiGFixH8txCXx7CrB" platfrom="wechat" platfrom_detial="wechat_one"><div class="wechat_one" onclick="simpleSubmit();"><i class="iconfont icon-weixin"></i><font>点击立即前往微信</font></div></div>');
            $workLinkHtml = Worklinkhtml::workLinkHtml($kfid);
        }
        $debug_time = time()+3600;
        $debug_sign = md5($kfid.$debug_time);
        $siteHtml = ["kfid"=>$workLinkHtml->kfid,"title"=>$workLinkHtml->title,"redirect_type"=>$workLinkHtml->redirect_type,"copyright"=>$workLinkHtml->copyright,"debug_time"=>$debug_time,"debug_sign"=>$debug_sign];
        $workLinkHtml = $workLinkHtml->html;
        return view("admin.wxkf.wxkf_update_html",["siteHtml"=>$siteHtml,"workLinkHtml"=>$workLinkHtml]);
    }

    public function wxkfHtmlPublish(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $kfid = $request->kfid;
        $workLink = Worklink::workLinkDetial($kfid);
        if (empty($workLink)) return OutputService::error("微信外链不存在");
        if ($workLink->users_id != $users_id) return OutputService::error("微信外链不存在");
        $memberOrder = Memberorders::ordersDetial($users_id);
        if (empty($memberOrder) || $memberOrder->end_time <= time()) return OutputService::error("请开通商家/旗舰版会员后操作!");
        if ($memberOrder->product_id == 5) return OutputService::error("自定义落地页仅支持商家/旗舰版会员!");
        Worklinkhtml::updateWorkLinkHtml($kfid,$request->title,$request->html,$request->redirect_type,$request->copyright);
        if ($request->type == "online") {
            HtmlossService::uploadKefuHtml($kfid);
            return OutputService::success("微信客服链接落地页发布成功!");
        }
        return OutputService::success("微信客服链接落地页更新成功!");
    }

    public function wxkfHtmlDetial(Request $request,$kfid)
    {
        $workLinkHtml = Worklinkhtml::workLinkHtml($kfid);
        if (empty($workLinkHtml)) return view('links.notice',["msg"=>"当前客服链接落地页未配置!"]);
        return view("business.wxkf.work_link",["workLinkHtml"=>$workLinkHtml]);
    }

    public function wxkfCropList(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $workCorps = Workcorp::userWorkCropList($users_id,$request->name);
        return view("admin.wxkf.work_crop",["workCorps"=>$workCorps]);
    }

    public function wxkfCropInstall(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $config = Config::get("weixin.work.wwdbc75e4a6e50a684");
        $workCount = Workcorp::userWorkCorpCount($users_id);
        if ($workCount >= 3) {
            return redirect("/admin/wxkf/wxkf_crop")->with("status","error")->with("msg","当前账号绑定的企业大于3个,暂不支持绑定新企业!");
        }
        $preAuthCode = WorkcustomService::getPreAuthCode($config["suite_id"]);
        $sessionInfo = ["auth_type"=>0];
        $redirect_uri = urlencode("https://bab.moreqifu.cn/admin/wxkf/corp_install_success");
        try {
            $installUrl = "https://open.work.weixin.qq.com/3rdapp/install?suite_id=".$config["suite_id"]."&pre_auth_code=".$preAuthCode["pre_auth_code"]."&redirect_uri=".$redirect_uri."&state=".$users_id;
        } catch (Exception $e) {
            $installUrl = "";
        }
        return view("admin.wxkf.work_crop_install",["installUrl"=>$installUrl]);
    }

    public function wxkfCropInstallSuccess(Request $request)
    {
        $users_id = Auth::user()->id;
        if ($users_id != $request->state) return back()->with("status","error")->with("msg","参数错误,请重新授权！");
        if (empty($request->auth_code)) return back()->with("status","error")->with("msg","授权信息错误,请重新授权！");
        $auth_code = $request->auth_code;
        $config = Config::get("weixin.work.wwdbc75e4a6e50a684");
        $bussinessInfo = WorkcustomService::getPermanentCode($auth_code,$config["suite_id"]);
        if (isset($bussinessInfo["errcode"]) && $bussinessInfo["errcode"] != 0) {
            $errmsg = WorkerrorService::getErrorMsg($bussinessInfo["errcode"]);
            return back()->with("status","error")->with("msg",$errmsg);
        }
        // 保存更新微信企业数据
        WorkdataService::workCorpInfo($bussinessInfo,$users_id,$config["suite_id"]);
        return redirect("/admin/wxkf/wxkf_crop")->with("status","success")->with("msg","企业微信绑定成功!");
    }

    public function wxkfCropDel(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $workCorp = Workcorp::getWorkCorpDetial($request->corp_id);
        if (empty($workCorp) || $workCorp->users_id != $users_id) return OutputService::error("企业不存在!");
        if ($workCorp->disable == 2) return OutputService::error("当前企业未卸载天天微客,请卸载后再执行操作!",[],1005);
        $workLink = Worklink::getUserWorkLinkCrop($users_id,$request->corp_id);
        if (!empty($workLink)) return OutputService::error("当前企业存在链接[".$workLink->remark."],请删除链接后再执行操作!");
        Workcorp::workCorpDelete($request->corp_id,$workCorp->suite_id);
        return OutputService::success("企业删除成功!");
    }

    public function workLinkBackSetting(Request $request,$kfid,$back_platfrom)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $workLink = Worklink::workLinkDetial($kfid);
        if (empty($workLink)) return redirect("/admin/wxkf/wxkf_list")->with("status","error")->with("msg","微信链接不存在!");
        if ($users->authority != 3 && $workLink->users_id != $users_id) return redirect("/admin/wxkf/wxkf_list")->with("status","error")->with("msg","微信链接不存在!");

        $platfroms = ["dy"=>"抖音","bd"=>"百度","ks"=>"快手","zh"=>"知乎","xmly"=>"喜马拉雅","bili"=>"哔哩哔哩","gdt"=>"广点通","vivo"=>"Vivo营销","oppo"=>"OPPO营销平台"];
        if (!isset($platfroms[$back_platfrom])) return redirect("/admin/wxkf/wxkf_list")->with("status","error")->with("msg","参数错误,请联系客服处理!");
        $workLinkBack = Worklinkback::getWorkLinkBackPlatfrom($kfid,$back_platfrom);
        $debug_time = time()+3600;
        $debug_sign = md5($kfid.$debug_time);
        $vivoAuth = 1;
        if (empty($workLinkBack)) {
            $transFormTargets = ["dy"=>"wechat","bd"=>"35","ks"=>"wechat_copy","zh"=>"get_cust","xmly"=>"4","bili"=>"FORM_SUBMIT","gdt"=>"CONSULT","vivo"=>"ADD_WECHAT","oppo"=>"104"];
            Worklinkback::createWorkLinkBack($kfid,$back_platfrom,"",1,100,"",$transFormTargets[$back_platfrom]);
            // if ($back_platfrom == "vivo") {
            //     $usersVivoBackInfo = Hkzsbackvivo::getusersVivoBackInfo($unitHkzs->users_id);
            //     if (!empty($usersVivoBackInfo)) {
            //         Hkzsback::siteListBackVivoUpdate($kfid,$back_platfrom,"","",$usersVivoBackInfo->client_id,$usersVivoBackInfo->secret);
            //     }
            // }
            $workLinkBack = Worklinkback::getWorkLinkBackPlatfrom($kfid,$back_platfrom);
        } else {
            // if ($back_platfrom == "vivo") {
            //     $workLinkVivo = Hkzsbackvivo::getVivoBackInfo($workLink->api_id);
            //     $vivoAuth = empty($workLinkVivo->bind_status) ? 1 : 2;
            // }
        }
        $usersLastDomain = Usersdomain::getLastUserDomain($workLink->users_id);
        return view('admin.wxkf_back.wxkf_lists_back_'.$back_platfrom,['workLinkBack'=>$workLinkBack,'workLink'=>$workLink,'platfrom'=>$platfroms[$back_platfrom],'back_platfrom'=>$back_platfrom,'debug_time'=>$debug_time,'debug_sign'=>$debug_sign,'usersLastDomain'=>$usersLastDomain,'vivoAuth'=>$vivoAuth]);
    }

    public function workLinkBackSettingSubmit(Request $request)
    {
        $kfid = $request->kfid;
        $back_platfrom = $request->back_platfrom;
        if (in_array($back_platfrom, ["dy"]) && empty($request->assets_id)) return OutputService::error("请输入广告ID!");
        if ($back_platfrom == "bd" && empty($request->other)) return OutputService::error("请输入API回调token!");
        if ($request->submit_rate > 100 && $request->submit_rate < 10) return OutputService::error("回调比例为10-100之间的整数！");
        $users = Auth::user();
        $users_id = $users->id;
        $workLink = Worklink::workLinkDetial($kfid);
        if (empty($workLink)) return OutputService::error("微信链接不存在!");
        if ($users->authority != 3 && $workLink->users_id != $users_id) return OutputService::error("微信链接不存在!");
        $assets_id = empty($request->assets_id) ? "" : $request->assets_id;
        $other = empty($request->other) ? "" : $request->other;
        $api_id = empty($request->api_id) ? "" : $request->api_id;
        $api_key = empty($request->api_key) ? "" : $request->api_key;
        $domain = empty($request->domain) ? "" : $request->domain;
        Worklinkback::workLinkBackUpdate($kfid,$back_platfrom,$assets_id,$request->submit_rate,$request->transform_target,$request->submit_type,$request->event_active,$other,$request->submit_time,$request->submit_browser,$api_id,$api_key,$domain);
        Cache::forget('wxkf_back_'.$back_platfrom.'_'.$kfid);
        return OutputService::success("回调配置保存成功！");
    }

    public function workLinkUrl(Request $request)
    {
        $users = Auth::user();
        if ($users->authority != 3) return redirect("/admin/wxkf/wxkf_list")->with("status","error")->with("msg","您无权执行本操作!");
        $workLinkUrls = Worklinkurl::getWorkLinkUrlList();
        return view("admin.wxkf.work_link_url",["workLinkUrls"=>$workLinkUrls]);
    }

    public function workLinkUrlAdd(Request $request)
    {
        $users = Auth::user();
        if ($users->authority != 3) return OutputService::error("您无权执行本操作!");
        $link_url = trim($request->link_url);
        Worklinkurl::createWorkLinkUrl($request->corp_id,$link_url);
        Cache::forget('work_link_url');
        return OutputService::success("客服链接添加成功!");
    }

    public function workLinkUrlDelete(Request $request)
    {
        $users = Auth::user();
        if ($users->authority != 3) return OutputService::error("您无权执行本操作!");
        Worklinkurl::deleteWorkLinkUrlId($request->id);
        Cache::forget('work_link_url');
        return OutputService::success("客服链接删除成功!");
    }

    public function workLinkUrlKefu(Request $request)
    {
        $corp_id = $request->corp_id;
        $list = WorkkfService::kfAccountList($corp_id,0);
        $accountLists = $list->account_list;
        foreach ($accountLists as $accountList) {
            $addway1 = WorkkfService::kfAddContactWay($corp_id,$accountList->open_kfid,"ttwl");
            dump($addway1->url);
        }
    }
}
